query("SELECT academic_year FROM calender ORDER BY sn DESC"); $academic_years = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); // Get classes $stmt = $DBcon->query("SELECT classid FROM class ORDER BY classid"); $class_options = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); } catch (PDOException $e) { error_log("Error fetching data: " . $e->getMessage()); $error = "Unable to fetch required data. Please try again."; } // Process form if submitted if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload'])) { $academic_year = sanitize_input($_POST['academic_year']); $class_id = sanitize_input($_POST['class_id']); // Validate CSRF token if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) { $upload_error = "Invalid security token."; } elseif (empty($academic_year) || empty($class_id)) { $upload_error = "Academic Year and Class are required."; } elseif (!isset($_FILES['excelFile']) || $_FILES['excelFile']['error'] !== UPLOAD_ERR_OK) { $upload_error = "Please select a valid file."; } else { // Process the file $result = processExcelFile($_FILES['excelFile'], $academic_year, $class_id, $DBcon); if ($result['success']) { $upload_success = true; $upload_message = "Successfully uploaded {$result['inserted']} students. "; if ($result['errors'] > 0) { $upload_message .= "{$result['errors']} records had errors."; } $error_list = $result['error_list']; } else { $upload_error = $result['message']; } } } function processExcelFile($file, $academic_year, $class_id, $DBcon) { $allowedTypes = ['text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; $allowedExtensions = ['csv', 'xls', 'xlsx']; $fileName = $file['name']; $fileTmpName = $file['tmp_name']; $fileSize = $file['size']; $fileError = $file['error']; // Check file extension $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (!in_array($fileExtension, $allowedExtensions)) { return ['success' => false, 'message' => 'Invalid file type. Please upload CSV or Excel files only.']; } if ($fileSize > 5 * 1024 * 1024) { // 5MB return ['success' => false, 'message' => 'File size must be less than 5MB.']; } if ($fileError !== UPLOAD_ERR_OK) { return ['success' => false, 'message' => 'File upload error.']; } // Parse the file $students = []; if ($fileExtension === 'csv') { $students = parseCSVFile($fileTmpName); } else { // For Excel files, convert to CSV first (simple approach) $students = parseExcelFileSimple($fileTmpName, $fileExtension); } if (empty($students)) { return ['success' => false, 'message' => 'No valid data found in the file. Please check the format.']; } // Insert into database return insertStudentsData($students, $academic_year, $class_id, $DBcon); } function parseCSVFile($filePath) { $students = []; if (($handle = fopen($filePath, "r")) !== FALSE) { $rowCount = 0; while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $rowCount++; // Skip header row (assuming first row is header) if ($rowCount === 1) continue; if (count($data) >= 2) { $fullname = trim($data[0]); $regno = trim($data[1]); // Only add if both fields are not empty if (!empty($fullname) && !empty($regno)) { $students[] = [ 'fullname' => $fullname, 'regno' => $regno ]; } } } fclose($handle); } return $students; } function parseExcelFileSimple($filePath, $extension) { // Simple approach: Use shell command to convert to CSV if available // This requires libreoffice or similar on server $students = []; if ($extension === 'xls' || $extension === 'xlsx') { // Try to use PHP's built-in CSV parser first // Some Excel files can be read as CSV $students = parseCSVFile($filePath); if (empty($students)) { // Alternative: Use simple text parsing for basic Excel files $students = parseExcelAsText($filePath); } } return $students; } function parseExcelAsText($filePath) { // Very basic Excel file parsing for simple files // This works only for simple, non-binary Excel files $students = []; $content = file_get_contents($filePath); // Look for data patterns (very basic) preg_match_all('/.*?.*?(.*?)<\/v>.*?.*?(.*?)<\/v>.*?<\/row>/is', $content, $matches); if (!empty($matches[1])) { for ($i = 0; $i < count($matches[1]); $i++) { $fullname = trim($matches[1][$i]); $regno = trim($matches[2][$i]); if (!empty($fullname) && !empty($regno)) { $students[] = [ 'fullname' => $fullname, 'regno' => $regno ]; } } } return $students; } function insertStudentsData($students, $academic_year, $class_id, $DBcon) { $inserted = 0; $errors = 0; $error_list = []; try { // Start transaction $DBcon->beginTransaction(); foreach ($students as $index => $student) { $fullname = sanitize_input($student['fullname']); $regno = sanitize_input($student['regno']); // Check if regno already exists $checkStmt = $DBcon->prepare("SELECT COUNT(*) FROM students_info WHERE regno = ?"); $checkStmt->execute([$regno]); $exists = $checkStmt->fetchColumn(); if ($exists > 0) { $errors++; $error_list[] = "Row " . ($index + 1) . ": Registration number '$regno' already exists"; continue; } // Insert into students_info $stmt = $DBcon->prepare(" INSERT INTO students_info (fullname, regno, class_id, admin_year) VALUES (?, ?, ?, ?) "); if ($stmt->execute([$fullname, $regno, $class_id, $academic_year])) { // Insert into promoted table $promotedStmt = $DBcon->prepare(" INSERT INTO promoted (regno, accademic_year, class_id) VALUES (?, ?, ?) "); $promotedStmt->execute([$regno, $academic_year, $class_id]); $inserted++; } else { $errors++; $error_list[] = "Row " . ($index + 1) . ": Failed to insert '$fullname'"; } } // Commit transaction $DBcon->commit(); return [ 'success' => true, 'total' => count($students), 'inserted' => $inserted, 'errors' => $errors, 'error_list' => $error_list ]; } catch (PDOException $e) { // Rollback on error $DBcon->rollBack(); error_log("Database error: " . $e->getMessage()); return [ 'success' => false, 'message' => 'Database error: ' . $e->getMessage() ]; } } ?> Upload Students - School Admin
Instructions

Create a CSV or Excel file with exactly 2 columns in this order:

  1. Column 1: Full Name (required)
  2. Column 2: Registration Number (required)

Note: Do not include header row. The first row should be data.

Example format:

John Doe,MMGSS/001/2025
Jane Smith,MMGSS/002/2025
Michael Johnson,MMGSS/003/2025
Upload Successful!

Errors:

Select Excel/CSV File

Maximum file size: 5MB

Supported formats: .csv, .xls, .xlsx
Copyright © 2018. All rights reserved. Hand-crafted & made with